//
//  BaiKeSecondClassesItemVC.m
//  BaseProject
//
//  Created by mac on 2020/12/22.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "BaiKeSecondClassesItemVC.h"
#import "BaiKeSecondClassesItemScrollView.h"
#import "BaiKeMainModel.h"
#import "BSTBitmapView.h"
#import "BaiKeMainCell.h"
//刷新
#import "AnimRefreshHeader.h"
#import "AnimRefreshFooter.h"
#import "QAPublishViewController.h"
//跳转
#import "BaiKeDetailVC.h"
@interface BaiKeSecondClassesItemVC ()<UITableViewDelegate,UITableViewDataSource,BSTBitmapViewDelegate>
@property(nonatomic,strong)BaiKeSecondClassesItemScrollView *topView;
@property(nonatomic,strong)UITableView *mainView;
@property(nonatomic,assign)NSInteger pageIndex;
@property(nonatomic,assign)NSInteger pageNumber;
@property(nonatomic,strong)BSTBitmapView *bitmapView;
@property(nonatomic,strong)NSMutableArray<BaiKeSubListDataListModel *> *dataSource;
@property(nonatomic,strong)NSString *keyword;
//用于计数
@property(nonatomic,assign)BOOL addObserver;
@end

@implementation BaiKeSecondClassesItemVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createProperty];
    [self createUI];
    [self createNetMethod];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"viewDidAppear");
    if (self.type == BaiKeSecondClassesItemVCTypeSearch && !self.addObserver) {
        self.addObserver = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchCallBack:) name:@"searchNoti" object:nil];
    }
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSLog(@"viewDidDisappear");
    if (self.type == BaiKeSecondClassesItemVCTypeSearch && self.addObserver) {
        self.addObserver = NO;
        [[NSNotificationCenter defaultCenter]removeObserver:self];
    }
}
- (void)dealloc
{
    NSLog(@"BaiKeSecondClassesItemVC ---dealloc");
}
- (void)realTimeSearchKeyword:(NSString *)keyword
{
    NSLog(@"%@",keyword);
    self.keyword = keyword;
}
- (void)createProperty
{
    self.pageIndex = 1;
    self.pageNumber = 10;
    
    if (self.viewHeight <= 0.0f) {
        self.viewHeight = HEIGHT - kTopHeight;
    }
}
- (void)searchCallBack:(NSNotification *)Noti
{
    NSLog(@"%@",Noti);
    self.keyword = [Noti.userInfo objectForKey:@"keyWord"];
    [self loadNewData];
}
- (void)createUI
{
    [self mainView];
    self.bitmapView.top = 0;
    self.bitmapView.type = BitmapViewTypeLoading;
    
    if (self.type == BaiKeSecondClassesItemVCTypeThreeList) {
        [self createNaviBarWithTitle:self.listModel.threeName backButtonBlock:nil];
        self.mainView.top = kTopHeight;
        self.mainView.height = HEIGHT - kTopHeight;
        self.bitmapView.height = self.mainView.height;
        self.topView.hidden = YES;
    }
    
    if (self.type == BaiKeSecondClassesItemVCTypeSearch) {
        self.mainView.top = 0;
        self.mainView.height = self.viewHeight;
        self.bitmapView.height = self.mainView.height;
        self.topView.hidden = YES;
    }
}
#pragma mark - setter
- (void)nativeJumpScrollTopView
{
    //是主动筛选
    [self loadNewData];
    [self.topView nativeJumpScrollTopView];
}
#pragma mark - 网络请求
- (void)createNetMethod
{
    [self createRefresh];
}
- (void)createRefresh
{
    self.mainView.mj_header = [AnimRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self loadNewData];//静态刷新
    //[self.mainView.mj_header beginRefreshing];
}
//下拉刷新
- (void)loadNewData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //恢复可刷新状态
        if (self.mainView.mj_footer) {
            [self.mainView.mj_footer removeFromSuperview];
        }
        [self endRefresh];
        //star
        self.pageIndex = 1;
        [self loadMyMessage];
    });
}
//上拉加载
- (void)loadMoreData
{
    self.pageIndex ++;
    [self loadMyMessage];
}
- (void)loadMyMessage
{
    //解决 没有三级分类 不必要的请求
    if (self.listModel.sysClassificationList.count <= 0 && self.type == BaiKeSecondClassesItemVCTypeMain) {
        [self refreshNoDataBitMapView];
        [self endRefresh];
        return;
    }
    WK(weakSelf)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSMutableDictionary *t = [NSMutableDictionary dictionary];
    [parameters setValue:t forKey:@"t"];
    [parameters setValue:[NSString stringWithFormat:@"%ld",(long)10] forKey:@"pageSize"];
    [parameters setValue:[NSString stringWithFormat:@"%ld",(long)self.pageIndex] forKey:@"pageNum"];
    switch (self.type) {
        case BaiKeSecondClassesItemVCTypeMain:
        {
            //获取scId
            for (NSInteger index = 0; index < self.listModel.sysClassificationList.count; index ++) {
                BaiKeMainClassesDataModel *listModel = self.listModel.sysClassificationList[index];
                if (listModel.isSelected) {
                    [t setValue:listModel.scId forKey:@"threeId"];
                    break;
                }
            }
        }
            break;
        case BaiKeSecondClassesItemVCTypeThreeList:
        {
            [t setValue:self.listModel.scId forKey:@"threeId"];
        }
            break;
        case BaiKeSecondClassesItemVCTypeSearch:
        {
            [t setValue:self.keyword forKey:@"title"];
        }
            break;
        default:
            break;
    }
    //获取scId
    NSLog(@"%@",parameters);
    [TTHttpManager postRequestWithUrl:[NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/userWeddingEncyclopedia/userWeddingList"] TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull responseObject) {
        BaiKeSubListModel *responModel = [BaiKeSubListModel modelWithJSON:responseObject];
        if (responModel.success) {
            if (weakSelf.pageIndex == 1)
            {
                //--------------头部刷新--------------//
                [weakSelf refreshHeadCode:responModel];
                //处理没有数据的占位图
                [weakSelf refreshNoDataBitMapView];
            } else {
                //--------------脚部刷新--------------//
                [weakSelf refreshFooterCode:responModel];
            }
        } else {
            [SVProgressHUD showWithStatus:responModel.message];
            [SVProgressHUD dismissWithDelay:1];
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD showWithStatus:@"请检查网络~"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}
- (void)endRefresh
{
    if (self.mainView.mj_header) {
        [self.mainView.mj_header endRefreshing];
    }
    if (self.mainView.mj_header) {
        [self.mainView.mj_footer endRefreshing];
    }
}
- (NSArray *)handleData:(BaiKeSubListModel *)dataModel
{
    for (NSInteger index = 0; index < dataModel.data.list.count; index ++) {
        BaiKeSubListDataListModel *listModel = dataModel.data.list[index];
        NSMutableAttributedString *titleAttributes = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",listModel.briefIntroduction]];
        titleAttributes.font = kFontRegular13;
        titleAttributes.color = rgba(102, 102, 102, 1);
        titleAttributes.lineSpacing = 5*ADAPTER_WIDTH;
        listModel.introductionHeight = [YYTextLayout layoutWithContainerSize:CGSizeMake(WIDTH - 52*ADAPTER_WIDTH, MAXFLOAT) text:titleAttributes].textBoundingSize.height;
        listModel.introductionHeight = MIN(56*ADAPTER_WIDTH, listModel.introductionHeight);
        listModel.cellHeight = listModel.introductionHeight + 59*ADAPTER_WIDTH;//14+35+10
        listModel.briefIntroduction_attributes = titleAttributes;
        listModel.createTime = @"";
    }
    return dataModel.data.list;
}
- (void)refreshHeadCode:(BaiKeSubListModel *)dataModel
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:[self handleData:dataModel]];
    //加载头部之类的
    
    //刷新mainView
    [self.mainView reloadData];
    [self endRefresh];
    //添加脚步刷新 会自动销毁替换的
    dispatch_async(dispatch_get_main_queue(), ^{
        //1.如果分页数量满额的
        //  1.1 如果contentSize.height 大与自身 则需要加入脚步
        //  1.2 如果contentSize.height 小与自身 则不需要加入脚步 请求下一个接口
        //2.如果分页数量小于满额
        //  2.1  如果contentSize.height 大与自身 则需要加入脚步 提醒没有更多了
        //  2.2  如果contentSize.height 小于自身 则不需要加入脚步
        //3.如果是0
        //  3.1  直接移除脚步 一个cell都没有要脚步干啥
        if (dataModel.data.list.count >= self.pageNumber) {
            if (self.mainView.contentSize.height > self.mainView.height) {
                MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                self.mainView.mj_footer = footer;
            } else {
                [self loadMoreData];
            }
        } else if (dataModel.data.list.count > 0){
            if (self.mainView.contentSize.height > self.mainView.height) {
                MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                [footer endRefreshingWithNoMoreData];
                self.mainView.mj_footer = footer;
            } else {
                if (self.mainView.mj_footer) {
                    [self.mainView.mj_footer removeFromSuperview];
                }
            }
        } else {
            if (self.mainView.mj_footer) {
                [self.mainView.mj_footer removeFromSuperview];
            }
        }
    });
}
- (void)refreshFooterCode:(BaiKeSubListModel *)dataModel
{
    [self.dataSource addObjectsFromArray:[self handleData:dataModel]];
    if (dataModel.data.list.count > 0) {
        [self.mainView reloadData];
        [self endRefresh];
    }
    //1.如果分页数量满额的 无需处理
    //  1.1 如果contentSize.height 大与自身  无任何操作
    //  1.2 如果contentSize.height 小与自身  请求下个接口
    //2.如果分页数量小于满额
    //  2.1  如果contentSize.height 大与自身  提醒没有更多了
    //  2.2  如果contentSize.height 小于自身 则不需要加入脚步
    dispatch_async(dispatch_get_main_queue(), ^{
        if (dataModel.data.list.count >= self.pageNumber) {
            if (self.mainView.contentSize.height > self.mainView.height) {
                MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                self.mainView.mj_footer = footer;
            } else {
                [self loadMoreData];
            }
        } else {
            if (self.mainView.contentSize.height > self.mainView.height) {
                [self.mainView.mj_footer endRefreshingWithNoMoreData];
            } else {
                if (self.mainView.mj_footer) {
                    [self.mainView.mj_footer removeFromSuperview];
                }
            }
        }
    });
}
#pragma mark - 占位图
- (void)refreshNoDataBitMapView
{
    //占位图
    if (self.dataSource.count == 0) {
        self.bitmapView.type = BitmapViewTypeNoData;
        if (self.type == BaiKeSecondClassesItemVCTypeSearch) {
            [self.bitmapView changeBaike];
        }
        [self.mainView addSubview:self.bitmapView];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.bitmapView.frame = self.mainView.bounds;
            self.bitmapView.origin = CGPointMake(0, self.mainView.tableHeaderView.height);
        });
    } else {
        self.bitmapView.type = BitmapViewTypeNormal;
        [self.view insertSubview:self.bitmapView belowSubview:self.mainView];
        dispatch_async(dispatch_get_main_queue(), ^{
             //留着扩大滑动范围用
            self.bitmapView.frame = self.mainView.frame;
        });
    }
}
- (void)refreshNetErrorBitMapView
{
    if (self.dataSource.count == 0) {
        self.bitmapView.type = BitmapViewTypeNetError;
        [self.mainView addSubview:self.bitmapView];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.bitmapView.frame = self.mainView.bounds;
            self.bitmapView.origin = CGPointMake(0, self.mainView.tableHeaderView.height);
        });
    } else {
        self.bitmapView.type = BitmapViewTypeNormal;
        [self.view insertSubview:self.bitmapView belowSubview:self.mainView];
        dispatch_async(dispatch_get_main_queue(), ^{
             //留着扩大滑动范围用
            self.bitmapView.frame = self.mainView.frame;
        });
    }
}
#pragma mark - BSTBitmapView代理
- (void)bstBitmapView:(BSTBitmapView *)bitmapView backType:(BitmapViewType)type
{
    if (type == BitmapViewTypeLoading) {
        NSLog(@"加载中....");
    } else if (type == BitmapViewTypeNetError || type == BitmapViewTypeServerCrash) {
        NSLog(@"网络错误");
        [self loadNewData];
    } else if (type == BitmapViewTypeNoData) {
        NSLog(@"没有数据");
        if (self.type == BaiKeSecondClassesItemVCTypeSearch) {
            QAPublishViewController *vc = [[QAPublishViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            [self loadNewData];
        }
    }
}

#pragma mark - UITableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaiKeMainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.listModel = self.dataSource[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaiKeDetailVC *vc = [[BaiKeDetailVC alloc]init];
    vc.listModel = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.dataSource[indexPath.row].cellHeight;
}
#pragma mark - lazy懒加载
- (UITableView *)mainView
{
    if (!_mainView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.height, WIDTH, self.viewHeight - self.topView.height) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        [tableView registerClass:[BaiKeMainCell class] forCellReuseIdentifier:@"Cell"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *))
        {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            tableView.estimatedRowHeight = 0;
            tableView.estimatedSectionFooterHeight = 0;
            tableView.estimatedSectionHeaderHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _mainView = tableView;
    }
    return _mainView;
}
- (BaiKeSecondClassesItemScrollView *)topView
{
    if (!_topView) {
        BaiKeSecondClassesItemScrollView *view = [[BaiKeSecondClassesItemScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 48*ADAPTER_WIDTH)];
        [self.view addSubview:view];
        view.listModel = self.listModel;
        WK(weakSelf)
        [view setCallBackSelectedModel:^(NSInteger selectedIndex) {
            [weakSelf loadNewData];
        }];
        _topView = view;
    }
    return _topView;
}
- (BSTBitmapView *)bitmapView
{
    if (!_bitmapView) {
        BSTBitmapView *view = [[BSTBitmapView alloc]initWithFrame:CGRectMake(0, 0, self.mainView.width, self.mainView.height)];
        [self.mainView addSubview:view];
        view.delegate = self;
        _bitmapView = view;
    }
    return _bitmapView;
}
- (NSMutableArray<BaiKeSubListDataListModel *> *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
@end
